package com.ruoyi.framework.security.filter;

import java.io.IOException;

import io.nop.api.core.auth.IUserContext;
import io.nop.api.core.context.ContextProvider;
import io.nop.api.core.context.IContext;
import io.nop.auth.core.login.UserContextImpl;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    TokenService tokenService;

    SecurityContextRepository securityContextRepository = new RequestAttributeSecurityContextRepository();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            // 如果不保存上下文，后续AnonymousFilter会从request中读取上下文导致权限检查失败
            securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);
            initUserContext(loginUser);
        }
        chain.doFilter(request, response);
    }

    void initUserContext(LoginUser loginUser) {
        UserContextImpl userContext = new UserContextImpl();
        String userName = loginUser.getUsername();
        userContext.setUserName(userName);
        userContext.setUserId(String.valueOf(loginUser.getUserId()));
        userContext.setDeptId(String.valueOf(loginUser.getDeptId()));
        userContext.setAccessToken(loginUser.getToken());
        userContext.setSessionId(loginUser.getToken());
        IUserContext.set(userContext);

        IContext ctx = ContextProvider.getOrCreateContext();
        ctx.setUserId(userContext.getUserId());
        ctx.setUserName(userName);
    }
}
